package assem.helpers;

import java.util.TreeMap;

import assem.Log;
import assem.enums.LogLevel;

// Thread safe global stats tracker
// Intended for gathering stats from disparate functions and threads
/// Not really used, however
public class Stats 
{
	static TreeMap<String,Integer> mStats = null;
	
	public Stats()
	{
	}
	public static void init()
	{
		if (mStats == null)
		{
			mStats = new TreeMap<String,Integer>();	
		}
	}
	public static void set(String key, int val)
	{
		synchronized(mStats)
		{
			mStats.put(key,val);
		}
	}	
	public static int get(String key)
	{
		synchronized(mStats)
		{
			return mStats.get(key);	
		}
	}
	public static void inc(String key,int amt)
	{
		synchronized(mStats)
		{
			if (!mStats.containsKey(key))
			{
				set(key,0);	
			}
			mStats.put(key,get(key) + amt);
		}
	}
	public static float avgFloat(String keyNum, String keyDenom) throws Exception
	{
		synchronized(mStats)
		{
			int num = mStats.get(keyNum);
			int denom = mStats.get(keyDenom);
			if (denom != 0)
			{
				return ((float)num)/((float)denom);
			}
			else
			{
				throw(new Exception("average with zero denom: " + keyDenom));	
			}
		}
		
	}
	public static void avg2Key(String keyNum, String keyDenom, String newKey) throws Exception
	{
		synchronized(mStats)
		{
			int num = mStats.get(keyNum);
			int denom = mStats.get(keyDenom);
			
			if (denom != 0)
			{
				int avg = num/denom;
				mStats.put(newKey,avg);
			}
			else
			{
				throw(new Exception("average with zero denom: " + keyDenom));	
			}
		}
		
	}	
	public static void printAll(LogLevel lvl)
	{
		for (String key : mStats.keySet())
		{
			int val = mStats.get(key);
			Log.msg(key + ":" + val,lvl);
		}
	}
}
